package com.example.test.security;

import lombok.Getter;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;

import javax.servlet.*;
import java.io.IOException;

/**
 * 自定义权限拦截器
 */
public class CustomFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
    @Getter
    private AccessDecisionManager accessDecisionManager;
    private SecurityMetadataSource securityMetadataSource;

    public CustomFilterSecurityInterceptor(AccessDecisionManager accessDecisionManager, SecurityMetadataSource securityMetadataSource) {
        this.accessDecisionManager = accessDecisionManager;
        this.securityMetadataSource = securityMetadataSource;
        setAccessDecisionManager(accessDecisionManager);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        invoke(new FilterInvocation(servletRequest, servletResponse, filterChain));
    }

    @SuppressWarnings("WeakerAccess")
    public void invoke(FilterInvocation invocation) throws IOException, ServletException {
        InterceptorStatusToken token = beforeInvocation(invocation);
        try {
            invocation.getChain().doFilter(invocation.getRequest(), invocation.getResponse());
        }finally {
            finallyInvocation(token);
            afterInvocation(token, null);
        }
    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return securityMetadataSource;
    }
}
